package com.mindflow.hbase.tutorials.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZookeeperFactory implements Watcher{


    private static final int SESSION_TIMEOUT = 5000;

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public static ZooKeeper getZooKeeper(String host){
        ZookeeperFactory zookeeperFactory = new ZookeeperFactory();
        try {
            return zookeeperFactory.connect(host);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("zookeeper call back!!");
        if(watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected){
            countDownLatch.countDown();
        }
    }

    private ZooKeeper connect(String host) throws IOException, InterruptedException {
        ZooKeeper zooKeeper = new ZooKeeper(host,SESSION_TIMEOUT,this);
        countDownLatch.await();
        System.out.println("init is over");
        return zooKeeper;
    }




}
